package com.dingup.paike.controller.lesson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dingup.api.Util.CalendarUtil;
import com.dingup.api.Util.RedisUtils;
import com.dingup.api.base.HttpResContent;
import com.dingup.api.bean.page.PageData;
import com.dingup.api.exception.ErrorCode;
import com.dingup.paike.adapter.pk.PkLessonInfoAdapter;
import com.dingup.paike.bean.requestBean.pk.PkLessonInfoRequestBean;
import com.dingup.paike.bean.requestBean.pk.PkLessonInfoSaveBatchRequestBean;
import com.dingup.paike.bean.requestBean.pk.PkLessonInfoScreenPageBean;
import com.dingup.paike.enums.LessonStatusEnum;
import com.dingup.paike.model.pk.PkLessonInfo;
import com.dingup.paike.service.pk.PkLessonInfoService;
import com.dingup.paike.util.OSSUtil;
import com.suyeer.basic.util.BHttpResUtil;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.dingup.api.base.BaseUtil.*;
import static com.dingup.paike.util.ConstUtil.REQUEST_PARAMETER_ID;
import static com.dingup.paike.util.ConstUtil.REQUEST_PARAMETER_LESSON_ID;

/**
 * Created by wancheng on 2018/9/26.
 */
@Controller
@RequestMapping("/lesson")
public class LessonController {
    private static Logger logger = LoggerFactory.getLogger(LessonController.class);
    @Autowired
    PkLessonInfoService pkLessonInfoService;

    @RequestMapping(value = "/save_lesson_info.do", method = RequestMethod.POST)
    public void saveLessonInfo(HttpServletRequest request,
                               HttpServletResponse response,
                               PkLessonInfoRequestBean pkLessonInfoRequestBean) {
        HttpResContent<Map<String, String>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("保存排课表单");
        try {
            check(pkLessonInfoRequestBean);
            String userId = RedisUtils.getInstance().getUserId(request);
            pkLessonInfoRequestBean.setOperaUserId(userId);
            PkLessonInfo res = pkLessonInfoService.save(pkLessonInfoRequestBean);
            Map<String, String> status = getReturnStatus(res);
            saveSuccessMsgAndData(hrc, status);
        } catch (InvalidCipherTextException e) {
            saveSimpleMsgAndData(hrc, ErrorCode.MESSAGE_ERROR_CODE, e);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }
    private Map<String, String> getReturnStatus(PkLessonInfo res) {
        Map<String, String> status = new HashMap<>();
        if (res.getIfPreLesson()) {
            status.put("lessonStatus", "UNSTART");
            return status;
        }
        Date currentDate = new Date();
        if (currentDate.before(res.getBeginTime())) {
            status.put("lessonStatus", "UNSTART");
        } else if (currentDate.before(res.getEndTime()) && currentDate.after(res.getBeginTime())) {
            status.put("lessonStatus", "IMPLEMENTING");
        } else if (currentDate.after(res.getEndTime())) {
            status.put("lessonStatus", "END");
        }
        return status;
    }

    @RequestMapping(value = "/update_lesson_info.do", method = RequestMethod.POST)
    public void updateLessonInfo(HttpServletRequest request,
                                 HttpServletResponse response,
                                 PkLessonInfoRequestBean pkLessonInfoRequestBean) {
        HttpResContent<Map<String, String>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("修改排课表单");
        try {
            logger.info("PkLessonInfoRequestBean={}", JSON.toJSONString(pkLessonInfoRequestBean));
            check(pkLessonInfoRequestBean);
            String userId = RedisUtils.getInstance().getUserId(request);
            pkLessonInfoRequestBean.setOperaUserId(userId);
            PkLessonInfo res = pkLessonInfoService.update(pkLessonInfoRequestBean);
            Map<String, String> status = getReturnStatus(res);
            saveSuccessMsgAndData(hrc, status);
        } catch (InvalidCipherTextException e) {
            saveSimpleMsgAndData(hrc, ErrorCode.MESSAGE_ERROR_CODE, e);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_pk_lesson_info_by_id.do", method = RequestMethod.POST)
    public void getPkLessonInfoById(HttpServletRequest request,
                                    HttpServletResponse response,
                                    Integer id) {
        HttpResContent<PkLessonInfoAdapter> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取排课信息");
        try {
            PkLessonInfoAdapter res = pkLessonInfoService.getPkLessonInfoAdapter(id);
            Date currentDate = new Date();
            if (currentDate.before(res.getBeginTime())) {
                res.setIfEndClass(false);
                res.setLessonStatus(LessonStatusEnum.LESSON_UNSTART);
            } else if (currentDate.before(res.getEndTime()) && currentDate.after(res.getBeginTime())) {
                res.setIfEndClass(false);
                res.setLessonStatus(LessonStatusEnum.LESSON_IMPLEMENTING);
            } else if (currentDate.after(res.getEndTime())) {
                res.setIfEndClass(true);
                res.setLessonStatus(LessonStatusEnum.LESSON_END);
            }
            pkLessonInfoService.initVideoInfo(res);
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/is_restore_completed.do", method = RequestMethod.POST)
    public void isRestoreCompleted(@RequestParam(REQUEST_PARAMETER_ID) Integer lessonId,
                                   HttpServletRequest request,
                                   HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("检查视频是否完成解冻");
        try {
            // check param
            checkParam(REQUEST_PARAMETER_LESSON_ID, lessonId);
            // do
            Boolean ret = OSSUtil.isRestoreCompleted("eeo-archive", "video/" + lessonId + "_0.mp4");
            saveSuccessMsgAndData(hrc, ret);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    @RequestMapping(value = "/get_pk_lesson_info_by_screen_bean.do", method = RequestMethod.POST)
    public void getPkLessonInfo(HttpServletRequest request,
                                HttpServletResponse response,
                                PkLessonInfoScreenPageBean pkLessonInfoScreenPageBean) {
        HttpResContent<PageData> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("班级信息--排课筛选");
        try {
            PageData data = pkLessonInfoService.getPkLessonInfoAdapter(pkLessonInfoScreenPageBean);
            saveSuccessMsgAndData(hrc, data);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/delete_batch_of_lesson.do", method = RequestMethod.POST)
    public void deleteBatchOfLesson(HttpServletRequest request,
                                    HttpServletResponse response,
                                    Integer[] lessonIds) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("排课--批量删除课节");
        try {
            if (lessonIds.length <= 0) {
                throw new Exception("参数不合法");
            }
            String userId = RedisUtils.getInstance().getUserId(request);
            pkLessonInfoService.deleteBatchOfLesson(lessonIds, userId);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/save_batch_of_lesson.do", method = RequestMethod.POST)
    public void saveBatchOfLesson(HttpServletRequest request,
                                  HttpServletResponse response,
                                  PkLessonInfoSaveBatchRequestBean bean) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("排课--批量排课");
        try {
            check(bean);
            //此处排课冲突检查
            List<PkLessonInfo> lessonInfos = bean.getPkLessonInfoArray();
            if (bean.getIfArrangeLessonForce() != null && !bean.getIfArrangeLessonForce()) {
                for (PkLessonInfo l : lessonInfos) {
                    pkLessonInfoService.checkTime(bean, l);
                }
            }
            String userId = RedisUtils.getInstance().getUserId(request);
            pkLessonInfoService.saveBatchOfLesson(bean, userId, bean.getIfSyncEeo());
            saveSuccessMsgAndData(hrc, true);
        } catch (InvalidCipherTextException e) {
            saveSimpleMsgAndData(hrc, ErrorCode.MESSAGE_ERROR_CODE, e);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/save_batch_of_lesson_multi_form.do", method = RequestMethod.POST)
    public void saveBatchOfLesson(HttpServletRequest request,
                                  HttpServletResponse response,
                                  String pkLessonInfoJson) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("排课--批量排课--多表单");
        try {
            List<PkLessonInfoSaveBatchRequestBean> requestBean = JSONArray.parseArray(pkLessonInfoJson, PkLessonInfoSaveBatchRequestBean.class);
            for (PkLessonInfoSaveBatchRequestBean bean : requestBean) {
                check(bean);
                //此处排课冲突检查
                List<PkLessonInfo> lessonInfos = bean.getPkLessonInfoArray();
                if (bean.getIfArrangeLessonForce() != null && !bean.getIfArrangeLessonForce()) {
                    for (PkLessonInfo l : lessonInfos) {
                        pkLessonInfoService.checkTime(bean, l);
                    }
                }
            }
            String userId = RedisUtils.getInstance().getUserId(request);
            pkLessonInfoService.saveBatchOfLessonMultiForm(requestBean, userId);
            saveSuccessMsgAndData(hrc, true);
        } catch (InvalidCipherTextException e) {
            saveSimpleMsgAndData(hrc, ErrorCode.MESSAGE_ERROR_CODE, e);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    private void check(PkLessonInfoRequestBean bean) throws Exception {
        Date currentDate = new Date();
        //通用参数参数检测
        if (!bean.getClass().equals(PkLessonInfoSaveBatchRequestBean.class)) {
            if (bean.getBeginTime() == null) {
                throw new Exception("开始时间为空");
            }
            //开始时间在当前时间之前,同步eeo为false
            if (currentDate.after(CalendarUtil.getTimeBeforMinute(new Date(bean.getBeginTime()), -20))) {
                bean.setIfSyncEeo(false);
            }
            if (bean.getEndTime() == null) {
                throw new Exception("结束时间为空");
            }
        }

        if (bean.getClassId() == null) {
            throw new Exception("班级为空");
        }
        //不是预排课
        if (!bean.getIfPreLesson()) {
            if (bean.getTeacherId() == null) {
                throw new Exception("老师为空");
            }
            if (bean.getStudentIds() == null) {
                throw new Exception("学生为空");
            }
            if (bean.getSubjectName() == null) {
                throw new Exception("科目为空");
            }
        }
        if (bean.getIfTranscribe() == null) {
            bean.setIfTranscribe(false);
        }
        if (bean.getIfPlayback() == null) {
            bean.setIfPlayback(false);
        }
        if (bean.getIfLive() == null) {
            bean.setIfLive(false);
        }
        if (bean.getIfClassFee() == null) {
            bean.setIfClassFee(false);
        }
        if (bean.getClassRoom() == null) {
            bean.setClassRoom("");
        }
    }

}

